<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>{{ loginTitle }}</span>
        </div>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="账号" prop="accountName">
          <el-input v-model="loginForm.accountName" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/modules/auth'
import CryptoJS from 'crypto-js'
import { ElForm } from 'element-plus'
import { LoginDto, LoginUser } from '@/api/login/type'
import { loginApi } from '@/api'

const router = useRouter()
const authStore = useAuthStore()
const loginFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const loginForm = reactive({
  accountName: '',
  password: ''
})

const rules = {
  accountName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const loginTitle = ref<string>(process.env.VITE_APP_TITLE || '管理系统')

const handleLogin = () => {
  loginFormRef.value!.validate((valid: boolean) => {
    if (valid) {
      //e10adc3949ba59abbe56e057f20f883e
      const loginDto: LoginDto = {
        accountName: loginForm.accountName,
        accountPassword: CryptoJS.MD5(loginForm.password).toString(),
        systemId: process.env.VITE_APP_SYSTEM_ID || '-1'
      }
      loginApi
        .doLogin(loginDto)
        .then((res: any) => {
          const loginUser: LoginUser = res || {}
          authStore.setUserInfo(loginUser)
          router.push('/')
          ElMessage.success('登录成功')
        })
        .catch((err) => {
          ElMessage.error('登录失败: ' + err || '登录失败')
        })
    }
  })
}
</script>

<style scoped lang="less">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
}

.card-header {
  display: flex;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
}
</style>
